package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("PurchaseadditiveService")
@Transactional

public class PurchaseadditiveServiceImpl extends CmiEmaService implements PurchaseadditiveService {
	public PurchaseadditiveServiceImpl() {
	}

	@Transactional
	public Purchaseadditive savePurchaseadditive(Purchaseadditive purchaseadditive) {

		if (purchaseadditive.getId() == null) {
			Additive additive = additiveDAO.findAdditiveById(purchaseadditive.getAdditive().getId());
			Producer producer = producerDAO.findProducerById(purchaseadditive.getProducer().getId());
			Supplier supplier = supplierDAO.findSupplierById(purchaseadditive.getSupplier().getId());
			Unit unit = unitDAO.findUnitById(purchaseadditive.getUnit().getId());

			Purchaseadditive existingPurchaseadditive = purchaseadditiveDAO.findPurchaseadditiveByPhysicalPrimaryKey(
					producer.getId(), supplier.getId(), additive.getId(), purchaseadditive.getDate());

			purchaseadditive.setAdditive(additive);
			purchaseadditive.setProducer(producer);
			purchaseadditive.setSupplier(supplier);
			purchaseadditive.setUnit(unit);

			if (isEquals(purchaseadditive, existingPurchaseadditive)) {
				return existingPurchaseadditive;
			}

			purchaseadditive = purchaseadditiveDAO.store(purchaseadditive);
			purchaseadditiveDAO.flush();

		} else {
			Purchaseadditive existingPurchaseadditive = purchaseadditiveDAO
					.findPurchaseadditiveByPrimaryKey(purchaseadditive.getId());

			purchaseadditive = purchaseadditiveDAO.store(purchaseadditive);
			purchaseadditiveDAO.flush();
		}

		return purchaseadditive;
	}

	public void deletePurchaseadditive(Purchaseadditive purchaseadditive) {
		purchaseadditiveDAO.remove(purchaseadditive);
		purchaseadditiveDAO.flush();
	}

	@Transactional
	public void deletePurchaseadditives(Set<Integer> deletePurchaseadditivesId) {
		Query query = purchaseadditiveDAO.createNamedQuery("deletePurchaseadditivesById", -1, -1);
		query.setParameter(1, deletePurchaseadditivesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Purchaseadditive> loadPurchaseadditives() {
		return purchaseadditiveDAO.findAllPurchaseadditives();

	}

	@Transactional
	public Set<Purchaseadditive> loadReferencePurchaseadditives(Set<Purchaseadditive> purchaseadditives) {
		Iterator<Purchaseadditive> purchaseadditivesIterator = purchaseadditives.iterator();
		Set<Purchaseadditive> referencedPurchaseadditives = new HashSet<>();
		while (purchaseadditivesIterator.hasNext()) {
			Purchaseadditive currentPurchaseadditive = purchaseadditivesIterator.next();

		}
		return referencedPurchaseadditives;
	}

	public Set<Purchaseadditive> loadPurchaseadditivesByIdSet(Set<Integer> purchaseadditiveIdSet) {

		Iterator<Integer> purchaseadditiveIdIterator = purchaseadditiveIdSet.iterator();
		Set<Purchaseadditive> purchaseadditiveSet = new HashSet<>();
		while (purchaseadditiveIdIterator.hasNext()) {
			Integer id = purchaseadditiveIdIterator.next();
			Purchaseadditive currentPurchaseadditive = purchaseadditiveDAO.findPurchaseadditiveById(id);
			purchaseadditiveSet.add(currentPurchaseadditive);
		}
		return purchaseadditiveSet;
	}

	@Transactional
	public List<Purchaseadditive> findAllPurchaseadditives(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Purchaseadditive>(
				purchaseadditiveDAO.findAllPurchaseadditives(startResult, maxRows));
	}

	@Transactional
	public Purchaseadditive findPurchaseadditiveByPrimaryKey(Integer id) {
		return purchaseadditiveDAO.findPurchaseadditiveByPrimaryKey(id);
	}

	@Transactional
	public Integer countPurchaseadditives() {
		return ((Long) purchaseadditiveDAO.createQuerySingleResult("select count(o) from Purchaseadditive o")
				.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countPurchaseadditives(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Purchaseadditive.class);
		return ((Long) purchaseadditiveDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countPurchaseadditivesByName(String queryName) {
		Query query = purchaseadditiveDAO.createNamedQuery("countPurchaseadditivesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countPurchaseadditivesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Purchaseadditive.class);
		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadPurchaseadditiveObjectReferencedSet(Purchaseadditive purchaseadditive) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (purchaseadditive.getAdditive() != null) {

			Set<Integer> additiveIds = new HashSet<Integer>();
			additiveIds.add(purchaseadditive.getAdditive().getId());
			objectReferencedSetMap.put("additiveIds", additiveIds);
		}
		if (purchaseadditive.getProducer() != null) {

			Set<Integer> producerIds = new HashSet<Integer>();
			producerIds.add(purchaseadditive.getProducer().getId());
			objectReferencedSetMap.put("producerIds", producerIds);
		}
		if (purchaseadditive.getSupplier() != null) {

			Set<Integer> supplierIds = new HashSet<Integer>();
			supplierIds.add(purchaseadditive.getSupplier().getId());
			objectReferencedSetMap.put("supplierIds", supplierIds);
		}
		if (purchaseadditive.getUnit() != null) {

			Set<Integer> unitIds = new HashSet<Integer>();
			unitIds.add(purchaseadditive.getUnit().getId());
			objectReferencedSetMap.put("unitIds", unitIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadPurchaseadditiveClassReferencedSet(Purchaseadditive purchaseadditive) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("additives", additiveDAO.findAllAdditives());
		classReferencedSetMap.put("producers", producerDAO.findAllProducers());
		classReferencedSetMap.put("suppliers", supplierDAO.findAllSuppliers());
		classReferencedSetMap.put("units", unitDAO.findAllUnits());

		return classReferencedSetMap;
	}

	public boolean isEquals(Purchaseadditive purchaseadditive, Object obj) {
		if (obj == purchaseadditive)
			return true;
		if (!(obj instanceof Purchaseadditive))
			return false;
		Purchaseadditive comparedPurchaseadditive = (Purchaseadditive) obj;
		if (!CheckPropertyEqual(purchaseadditive.getProducer().getId(),
				comparedPurchaseadditive.getProducer().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(purchaseadditive.getSupplier().getId(),
				comparedPurchaseadditive.getSupplier().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(purchaseadditive.getAdditive().getId(),
				comparedPurchaseadditive.getAdditive().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(purchaseadditive.getDate(), comparedPurchaseadditive.getDate())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

